package com.hjw.dynamicdatasource.config;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author ivan
 */
@Component
public class DynamicDataSourceManager {

    private HikariDataSource dataSource;
    @Value("${spring.datasource.url}")
    String url;
    @Value("${spring.datasource.username}")
    String username;
    @Value("${spring.datasource.password}")
    String password;
    @Value("${spring.datasource.driverClassName}")
    String driverClassName;

    public DynamicDataSourceManager() {}

    @PostConstruct
    void init() throws SQLException {
        refreshDataSource(url, username, password, driverClassName);
    }

    public DataSource refreshDataSource(String url, String username, String password, String driverClassName) throws SQLException {
        // 关闭旧实例
        if (dataSource != null && !dataSource.isClosed()) {
            dataSource.close();
        }

        HikariConfig config = new HikariConfig();
        config.setPoolName("HikariPool-1");
        config.setJdbcUrl(url);
        config.setUsername(username);
        config.setPassword(password);
        config.setDriverClassName(driverClassName);
        config.setSchema("public");
        dataSource = new HikariDataSource(config);
        // 清除动态服务的缓存
        return dataSource;
    }

    public DataSource getDataSource() {
        return dataSource;
    }

    public void clearDataSource() {
        dataSource.close();
    }
}